<!--
 * @Author: WangShuai 1830773767@qq.com
 * @Date: 2025-06-16 18:50:11
 * @LastEditors: WangShuai 1830773767@qq.com
 * @LastEditTime: 2025-06-18 10:30:28
 * @FilePath: \vue3_admin_template\project\src\views\threeScene\initScene.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div ref="container" class="three-container"></div>
</template>

<script setup lang="ts">
import {} from 'vue'

import { ref, onMounted, onUnmounted } from 'vue'
import useSceneStore from '@/store/modules/threeScene'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

let setScene = useSceneStore()
const container = ref()
let scene: any, camera: any, renderer: any, controls: any

// 初始化Three.js场景
const initThreeScene = () => {
  // 创建场景
  scene = new THREE.Scene()
  scene.background = new THREE.Color(0xf0f0f0)

  // 创建相机
  camera = new THREE.PerspectiveCamera(
    75,
    container.value.clientWidth / container.value.clientHeight,
    0.1,
    1000,
  )
  camera.position.z = 5
  // 创建渲染器
  renderer = new THREE.WebGLRenderer({ antialias: true })
  renderer.setSize(container.value.clientWidth, container.value.clientHeight)
  renderer.setPixelRatio(window.devicePixelRatio)

  // 添加渲染器DOM到容器
  container.value.appendChild(renderer.domElement)
  // 添加轨道控制器
  controls = new OrbitControls(camera, renderer.domElement)
  controls.enableDamping = true
  camera.position.set(6.031, 1.39, -5.0)
  controls.enablePan = false
  controls.enableZoom = false //鼠标禁止缩放
  controls.minPolarAngle = (80 * Math.PI) / 180
  controls.maxPolarAngle = (80 * Math.PI) / 180
  // 动画循环
  const animate = () => {
    if (useSceneStore().tween) {
      useSceneStore().tween.update()
    }
    camera.lookAt(0, 0, 0)
    camera.updateProjectionMatrix()
    // 更新控制器
    controls.update()
    // 渲染场景
    renderer.render(scene, camera)
    requestAnimationFrame(animate)
  }

  animate()
  setScene.setSceneFn(scene)
}

// 响应窗口大小变化
const handleResize = () => {
  if (camera && renderer) {
    camera.aspect = container.value.clientWidth / container.value.clientHeight
    camera.updateProjectionMatrix()
    renderer.setSize(container.value.clientWidth, container.value.clientHeight)
  }
}

onMounted(() => {
  initThreeScene()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 清理资源
  if (controls) controls.dispose()
  if (renderer) renderer.dispose()
  window.removeEventListener('resize', handleResize)

  // 移除DOM元素
  if (container.value && renderer) {
    container.value.removeChild(renderer.domElement)
  }
})
</script>

<style scoped>
.three-container {
  width: 100%;
  height: 100vh;
  /* min-height: 400px; */
}
</style>
